#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_SIZE 1024

typedef struct node {
	int length;
	char *str;

	struct node *next;
}line;

int main()
{
	char *buf;
	buf = malloc (MAX_SIZE);

	FILE *file;

	line *iterator, *head = NULL, *active, *prev;

	file = fopen ("file-to-sort", "r");

	if (file) {
			buf = fgets (buf, MAX_SIZE, file);
			while (buf && buf[0]) {
				//printf ("Analyzing string: %s\n", buf);
				iterator = malloc (sizeof(line));
				iterator->length = strlen (buf);
				iterator->str = malloc (iterator->length);
				strcpy(iterator->str, buf);

				if (head) {
					active = head; prev = NULL;
					while (active) {
						if (active->length >= iterator->length) {
							if (prev) {
								prev->next = iterator;
								iterator->next = active;
							} else {
								head = iterator;
								head->next = active;
							}
							active = prev = NULL;
						} else {
							prev = active;
							active = active->next;
						}
					}

					if (!active && prev) {
						prev->next = iterator;
					}


				} else {
					head = iterator;
					head->next = NULL;
				}

				
				buf = fgets (buf, MAX_SIZE, file);
			}
	}

	active = head;
	while (active) {
		printf ("%s\n", active->str);
		active = active->next;
	}


	return 0;
}
